package bg.code.commons.builder.templte;

import bg.code.commons.builder.utils.FileUtil;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.StringWriter;
import java.nio.file.Path;
import java.util.Map;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/3/18
 * 描述：
 */
public class VelocityTemplateEngine implements ITemplteEngine {

    private VelocityEngine ve = new VelocityEngine();

    public VelocityTemplateEngine() {
        this.ve.setProperty("resource.loader", VelocityTemplateResourceLoader.class.getName());
        this.ve.setProperty("runtime.log", "startup_wizard_vel.log");
        this.ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.CommonsLogLogChute");
        this.ve.setProperty("runtime.log.logsystem.commons.logging.name", "initial_wizard_velocity");
        this.ve.init();
    }

    @Override
    public String render(String paramString, Map<String, Object> paramMap) throws Exception {
        Template t = this.ve.getTemplate(paramString);
        VelocityContext context = new VelocityContext();
        paramMap.forEach((key, val) -> {
            context.put(key, val);
        });

        StringWriter writer = new StringWriter();
        t.merge(context, writer);
        return writer.toString();
    }

    @Override
    public Path renderToFile(String paramString, Map<String, Object> paramMap, Path path) throws Exception {
        Path floderPath = path.getParent();
        if (!floderPath.toFile().exists()) {
            floderPath.toFile().mkdirs();
        }

        FileUtil.strToFile(this.render(paramString, paramMap), path.toFile());
        return floderPath;
    }
}
